package org.jmc.refmanager.web.wicket.page.panel;

import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.Component.IVisitor;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.jmc.refmanager.domain.dao.QueryParam;
import org.jmc.refmanager.domain.model.OrgUnit;
import org.jmc.refmanager.domain.model.filter.OrgUnitFilter;
import org.jmc.refmanager.security.SecurityHelper;
import org.jmc.refmanager.util.Util;
import org.jmc.refmanager.web.wicket.behavior.DisableEnterKeyBehavior;
import org.jmc.refmanager.web.wicket.provider.SortableServiceDataProvider;

/**
 */
public abstract class SelectParentPanel1 extends Panel {
	private static final long serialVersionUID = 1L;

	final QueryParam<OrgUnit> queryParams = new QueryParam<OrgUnit>();
	
	/**
	 * Methode que la page principale va implementer la persistance
	 * 
	 * @param target
	 */
	public abstract void onSave(AjaxRequestTarget target); 

	
	private final IModel<OrgUnit> searchModel;
	
	/**
	 * 
	 * @param target
	 */
	public abstract void onCancel(AjaxRequestTarget target); 

	public SelectParentPanel1(String id, final IModel<OrgUnit> targetModel) {
		this(id, new CompoundPropertyModel<OrgUnit>(new OrgUnit()), targetModel);
	}
	/**
	 * 
	 * @param id
	 * @param searchModel
	 * @param targetModel
	 */
	public SelectParentPanel1(String id, IModel<OrgUnit> searchModel, final IModel<OrgUnit> targetModel) {
		super(id, new CompoundPropertyModel<OrgUnit>(searchModel));
		setOutputMarkupId(true);
		final String matricule = SecurityHelper.getAuthentication().getName();
		
		this.searchModel = searchModel;
		
		Form<OrgUnit> form = new Form<OrgUnit>("searchForm", searchModel);
		form.setOutputMarkupId(true);
		add(form);

		TextField<String> codePostal = new TextField<String>("codePostal");
		codePostal.setOutputMarkupId(true);
		form.add(codePostal);

		TextField<String> codeUO = new TextField<String>("codeUO");
		codeUO.setOutputMarkupId(true);
		form.add(codeUO);

		TextField<String> libCourt = new TextField<String>("libCourt");
		libCourt.setOutputMarkupId(true);
		form.add(libCourt);

		TextField<String> libLong = new TextField<String>("libLong");
		libLong.setOutputMarkupId(true);
		form.add(libLong);

//		OrgUnit searchedService = (OrgUnit) getDefaultModelObject();
//		queryParams.setCriteriaExample(searchedService);
		queryParams.setExcludeProperties(OrgUnitFilter.filterSearchForm());
		
		SortableServiceDataProvider dp = new SortableServiceDataProvider(queryParams, matricule);
		
		final DataView<OrgUnit> dataView = new DataView<OrgUnit>("services", dp) {
			private static final long serialVersionUID = 1L;

			@Override
		    public boolean isVisible() {
				return this.getItemCount() > 0;
			}

			@Override
			protected void populateItem(Item<OrgUnit> item) {
				final OrgUnit service = item.getModelObject();
				
				item.add(new Label("codeUO", new PropertyModel<String>(service, "codeUO")));
				
				MarkupContainer selectLink = new AjaxLink<Integer>("selectLink", new PropertyModel<Integer>(service, "id")) {
					private static final long serialVersionUID = 1L;

					@Override
					public void onClick(AjaxRequestTarget target) {
						targetModel.getObject().setParent(service);
						// Reinitialise le modele
						SelectParentPanel1.this.searchModel.setObject(new OrgUnit());
						// Supprime le critere de recherche
						queryParams.setCriteriaExample(null);
						// Delegation e la methode onSave()
						onSave(target);
					}
				}.add(new Label("libCourt", service.getLibCourt()));
				item.add(selectLink);
				
				item.add(new Label("libLong", service.getLibLong()));
				item.add(new Label("codePostal", service.getCodePostal()));
			}
		};

		dataView.setItemsPerPage(20);
		dataView.setOutputMarkupId(true);
		add(dataView);

        final Label noResultLabel = new Label("noResult", "Aucun résultat ne correspond à votre recherche");
        noResultLabel.setVisible(dataView.getItemCount()==0);
        add(noResultLabel);

		AjaxPagingNavigator navigator = new AjaxPagingNavigator("navigator", dataView) {
			private static final long serialVersionUID = 1L;
			
			@Override
		    public boolean isVisible() {
				noResultLabel.setVisible(dataView.getItemCount()==0);
		        return dataView.getItemCount() > 0;
		    }
		};
		navigator.setOutputMarkupId(true);
		add(navigator);

		// Supprime la soumission du formulaire si on appuie sur "Entree"
		form.visitChildren(FormComponent.class, new IVisitor<Component>() {
			@Override
			public Object component(Component component) {
				if (!(component instanceof Button))
					component.add(new DisableEnterKeyBehavior());

				return IVisitor.CONTINUE_TRAVERSAL;
			} 
		});

		form.add(new AjaxButton("btnSearch", form) {
			private static final long serialVersionUID = 1L;

			@Override
			public void onSubmit(AjaxRequestTarget target, Form<?> form) {
				String libCourt = form.get("libCourt").getDefaultModelObjectAsString();
				String libLong = form.get("libLong").getDefaultModelObjectAsString();
				
				OrgUnit example = new OrgUnit();
				example.setCodePostal(form.get("codePostal").getDefaultModelObjectAsString());
				example.setCodeUO(form.get("codeUO").getDefaultModelObjectAsString());
		        if (!Util.isEmptyOrBlank(libCourt)) {
		        	example.setLibCourt("%" + libCourt);
		        }
		        if (!Util.isEmptyOrBlank(libLong)) {
			        example.setLibLong("%" + libLong);
		        }
				queryParams.setCriteriaExample(example);
				
				// Permet de rafraecher les donnees du panneau
				target.addComponent(SelectParentPanel1.this);
			}
		});
		
		AjaxButton btnCancel = new AjaxButton("btnCancel", form) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				form.clearInput();
				// Reinitialise le modele
				SelectParentPanel1.this.searchModel.setObject(new OrgUnit());
				// Supprime le critere de recherche
				queryParams.setCriteriaExample(null);
				onCancel(target);
			}
		};
		// Pas de validation
		btnCancel.setDefaultFormProcessing(false);
		form.add(btnCancel);
	}
}

